"use strict";
!(function($) {
    var pluginName = "weuiUpload",
        defaults   = {
        	title:'图片上传',//上传标题
            inputName: 'files', // 上传按钮名，即input[type=file]的name值
            imageUrl: [], // 已上传的图片连接
            maxNum: 5, // 最多允许上传个数
            error: $.noop, // 上传失败时的回调函数
        };

    function Plugin(element, options) {
        this.element   = element;
        this.settings  = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name     = pluginName;
        this.code = 0;
        this.msg  = '';
        this.init();
    }

    Plugin.prototype = {
        init: function() {
            var $self = this,
                $this = $(this.element),
                $imageUrl = $self.settings.imageUrl;

            $self.createSectionBox();

            $this.find(".weui-uploader__input-box").on('click', function() {
                $self.selectFile();
            });
        },

        /**
         * 创建容器盒子
         * @returns {*|jQuery|HTMLElement}
         */	        
        createSectionBox: function() {
            var $self = this,
                $this = $(this.element),
                $fileInput  = $self.settings.fileInput,
                $imageUrl = $self.settings.imageUrl,
                $inputName = $self.settings.inputName,

                // 一次构建
                $hdTitleBox = $('<div class="weui-uploader__hd"><p class="weui-uploader__title">' + $self.settings.title + '</p><div class="weui-uploader__info">' + $imageUrl.length + '/' + $self.settings.maxNum + '</div></div>'),
                $hdBox = $('<div class="weui-uploader__bd"></div>'),
                $hdBoxInput = $('<div class="weui-uploader__input-box"></div>'),

                // 容器
                $hdBoxUl = $('<ul class="weui-uploader__files ' + $inputName + '-ulDiv"></ul>'),
                $hdBoxHiddenInput = $('<div class="' + $inputName + '-inputDev"></div>');

            // 装载已存在数据
            if ($imageUrl.length > 0) {
            	$.each($imageUrl, function(i, item) {
            		var $li = $('<li class="weui-uploader__file ' + $inputName + '-del' + i + '"></li>'),
            			$img = $('<img width="96" height="96">'),
            			$input = $('<input type="hidden" name="' + $inputName + '[]" class="' + $inputName + '-del' + i + '">');

            		$img.attr('src', item);
            		$img.appendTo($li);
            		$li.append("<span class='iconfont icon-delete' data-index='" + i + "'></span>");
            		$li.appendTo($hdBoxUl);

            		$input.val(item);
            		$input.appendTo($hdBoxHiddenInput);
            	});
            }

            $hdBoxUl.appendTo($hdBox);
            $hdBoxInput.appendTo($hdBox);
            $hdBoxHiddenInput.appendTo($hdBox);

            $hdTitleBox.appendTo($this);
            $hdBox.appendTo($this);

            // 删除
            $hdBoxUl.find('.icon-delete').on('click', function (event) {
				event.stopPropagation();
				var index = $(this).data('index');
				$hdBoxUl.find('.' + $inputName + '-del' + index).remove();
				$hdBoxHiddenInput.find('.' + $inputName + '-del' + index).remove();

				$self.setUploaderInfo();
            });

            // 预览
            $hdBoxUl.find('img').on('click', function (event) {
            	event.stopPropagation();
		        var id = $(this).attr('src');
	            var nowServer = [];
	            $hdBoxUl.find('img').each(function(){
	                nowServer.push($(this).attr('src'));
	            });
	            wx.previewImage({
	                current: id,
	                urls: nowServer
	            });
            });
        },

        /**
         * 选择文件
         * @returns {boolean}
         */
        selectFile: function() {
            var $self = this,
                $this = $(this.element),
                $inputName = $self.settings.inputName,
                $maxNum  = $self.settings.maxNum,
                $imageUrl = $self.settings.imageUrl,
                wxCount = 0;

            var $liTag = $this.find('li');
            if ($liTag.length < $maxNum) {
            	wxCount = $maxNum - $liTag.length;
            }

            if (wxCount == 0) {
                $self.callError("302", "上传图片数目不能超过" + $maxNum + "个");
                return;
            }

            // 容器
            var $hdBoxUl = $this.find('.' + $inputName + '-ulDiv');
            var $hdBoxHiddenInput = $this.find('.' + $inputName + '-inputDev');

			wx.chooseImage({
                count: wxCount,
                success: function (res) {
                    $.each(res.localIds, function(index, val) {
                    	index = $liTag.length + index;
                		var $li = $('<li class="weui-uploader__file ' + $inputName + '-del' + index + '"></li>'),
                			$img = $('<img width="96" height="96">'),
                			$input = $('<input type="hidden" name="' + $inputName + '[]" class="' + $inputName + '-del' + index + '">');

                		$img.attr('src', val);
                		$img.appendTo($li);
                		$li.append("<span class='iconfont icon-delete' data-index='" + index + "'></span>");
                		$li.appendTo($hdBoxUl);

                        var upload_voice_localId = val;
                        wx.uploadImage({
                            localId: upload_voice_localId,
                            success: function (msg) {
                                $imageUrl.push(msg.serverId);
		                		$input.val(msg.serverId);
		                		$input.appendTo($hdBoxHiddenInput);
                            },
                            fail: function (msg) {
                                $.alert(JSON.stringify(msg));
                            }
                        });
                    });

                    $self.setUploaderInfo();
                }
            });

            // 删除
            $hdBoxUl.find('.icon-delete').on('click', function (event) {
				event.stopPropagation();
				var index = $(this).data('index');
				$hdBoxUl.find('.' + $inputName + '-del' + index).remove();
				$hdBoxHiddenInput.find('.' + $inputName + '-del' + index).remove();

				$self.setUploaderInfo();
            });

            // 预览
            $hdBoxUl.find('img').on('click', function (event) {
            	event.stopPropagation();
		        var id = $(this).attr('src');
	            var nowServer = [];
	            $hdBoxUl.find('img').each(function(){
	                nowServer.push($(this).attr('src'));
	            });
	            wx.previewImage({
	                current: id,
	                urls: nowServer
	            });
            });
        },

        // 更新上传数量
        setUploaderInfo: function () {
            var $self = this,
                $this = $(this.element),
                $inputName = $self.settings.inputName,
                $maxNum = $self.settings.maxNum,
        		$hdBoxUl = $this.find('.' + $inputName + '-ulDiv');

        	$this.find('.weui-uploader__info').text($hdBoxUl.children('li').length + '/' + $maxNum);
        },

        /**
         * 调用error函数
         * @param $code
         * @param $msg
         */
        callError: function($code, $msg) {
            var $self  = this,
                $error = $self.settings.error;

            $self.code = $code;
            $self.msg  = $msg;
            $error($self);
        }
    };

    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin(this, options));
            }
        });
    };
})(jQuery, window, document);